package hwcobs

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
	"github.com/spf13/viper"
	"strings"
)

func InitObs(akT, skT, endpointT, bucketT, cdnUrlT string) {
	ak = akT
	sk = skT
	endpoint = endpointT
	bucket = bucketT
	cdnUrl = cdnUrlT
}

var (
	ak       string
	sk       string
	endpoint string
	bucket   string
	cdnUrl   string
)

const (
	UrlExp = 7 * 86400 // 七天
)

//func GetClient() (*obs.ObsClient, error) {
//	var ak = "NKP1XP5AJMZPTWIXAZST"
//	var sk = "S6wXwgKufXuJPTxZnbhEghFEGV2z7PNWY4HecLHR"
//	var endpoint = "https://obs.cn-east-3.myhuaweicloud.com"
//	// 创建ObsClient结构体
//	return obs.New(ak, sk, endpoint)
//}

// pwd 源文件，key URL访问目录
func PutFile(pwd, key string) error {
	input := &obs.PutFileInput{}
	input.Bucket = bucket
	input.Key = key
	input.SourceFile = pwd // localfile为待上传的本地文件路径，需要指定到具体的文件名
	obsClient, err := obs.New(ak, sk, endpoint)
	if err != nil {
		return err
	}
	defer obsClient.Close()

	_, err = obsClient.PutFile(input)

	if err == nil {
		return nil
		// fmt.Printf("RequestId:%s\n", output.RequestId)
	} else {
		return err
		//if obsError, ok := err.(obs.ObsError); ok {
		//	fmt.Println(obsError.Code)
		//	fmt.Println(obsError.Message)
		//} else {
		//	fmt.Println(err)
		//}
	}
}

// GetCompleteUrl 获取华为云完整访问路径， true获取私有， false获取公有
func GetCompleteUrl(path string, flag bool) (string, error) {
	if flag { // 私有
		return CreateSignedUrl(path)
	}

	return viper.GetString("hwc.obs.cdnurl") + "/" + path, nil
}

func CreateSignedUrl(key string) (string, error) {
	putObjectInput := &obs.CreateSignedUrlInput{
		Method: obs.HTTP_GET,
		Bucket: bucket,
		Key:    key,
		// SubResource: "",
		Expires:     UrlExp,
		Headers:     nil,
		QueryParams: nil,
	}

	obsClient, err := obs.New(ak, sk, endpoint)
	if err != nil {
		return "", err
	}
	defer obsClient.Close()

	putObjectOutput, err := obsClient.CreateSignedUrl(putObjectInput)
	if err == nil {
		// todo 返回的url不是自定义的
		rf := fmt.Sprintf("https://%s.obs.cn-east-3.myhuaweicloud.com:443", bucket)
		return strings.Replace(putObjectOutput.SignedUrl, rf, cdnUrl, 1), nil
		//fmt.Printf("SignedUrl:%s\n", putObjectOutput.SignedUrl)
		//fmt.Printf("ActualSignedRequestHeaders:%v\n", putObjectOutput.ActualSignedRequestHeaders)
	}
	return "", err
}
